
/**
 * Created by wangjiakun on 2018/3/16 0016.
 */
import React from 'react';
import {connect} from 'react-redux';

import { messages, getApprovelHistory } from 'share/common';
import {Row, Col, Spin, Divider, Input, DatePicker, InputNumber, Form, Affix, Button, Card, Select,message, Popover} from 'antd';
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;

import moment from 'moment';
import debounce from 'lodash.debounce'
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'
import baseService from "share/base.service";

class TravelTrain extends React.Component {
  supply = {};
  searchType = "standard";
  intEnable = true;//是否可选到国际
  // 火车行程没有往返
  clearHistory = false;//是否切换供应商的时候直接清空地址
  startDate = "";
  endDate = "";

  constructor(props) {
    super(props);
    this.state = {
      params:{},//接收父组件的参数
      editing:false,//是否是编辑状态页，默认是新建页
      formCtrl:{},
      supplies: [],//供应商数据
      trainSeatClass: [], //火车座席数据
      currentIndex: 0,//当前供应商数组下标
      isLoading: false,//提交时是否loading提示
      cityFromSearchResult: [],//出发地
      cityToSearchResult: [],//目的地
      selectFromCity:{},//选择的出发城市
      selectToCity:{},//选择的目的城市
      isStandard:false,//是否走差旅标准,
      promptList: [], //行程提示语的配置
      currencyList: [],//货币列表
    };
  }

  componentWillMount() {
    let tempMap = this.props.params['travelInfo']['customFormPropertyMap'];
    let obj = tempMap['application.property.control.fields.train'] ? JSON.parse(tempMap['application.property.control.fields.train']) : travelUtil.getSetDataByTravelType('train');
    let isStandard = tempMap['ca.travel.applypolicy.enable'] ? JSON.parse(tempMap['ca.travel.applypolicy.enable']) : false;
    let promptList = tempMap['travel.itinerary.tips'] ? JSON.parse(tempMap['travel.itinerary.tips']) : [];
    this.setState({
      promptList,
      params:this.props.params,
      formCtrl:obj,
      isStandard:isStandard
    });
    this.getCurrencyList();//获取货币列表
    // this.getSupplies(2002);
    // this.getTrainSeat();
    this.startDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'start_date');
    this.endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'end_date');
    this.endDate = moment(this.endDate).format('YYYY-MM-DD');
    this.endDate = travelUtil.getAfterDate(1,this.endDate);
  };

  componentWillReceiveProps(){
    if(this.props.params.isResetTrain){
      this.resetForm();
      delete this.props.params.isResetTrain;
      return;
    }
    this.startDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date');
    this.endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
    this.endDate = moment(this.endDate).format('YYYY-MM-DD');
    this.endDate = travelUtil.getAfterDate(1, this.endDate);
    let editData = travelUtil.isEmpty(this.props.params.editTrain);
    if(!editData.isEmpty && !this.state.editing){
      let num = 0;
      this.state.supplies.map((m, index) => {
        if(m.supplierOID === editData.supplierOID){
          num = index;
          this.supply = m;
          if (this.supply.function && this.supply.function[0]) {
            this.searchType = 'standard';//this.supply.function[0].locationVendorType;
            this.intEnable = this.supply.function[0].intEnable;
          } else {
            this.searchType = 'standard';
            this.intEnable = true;
          }
        }
      })
      this.setState({
        editing:true,
        currentIndex:num,
        selectFromCity:{vendorAlias:editData.fromCity,code:editData.fromCityCode},
        selectToCity:{vendorAlias:editData.toCity,code:editData.toCityCode},
      },()=>{
        this.props.form.resetFields();
      })
    }
  };

  disabledDate = (current) =>{
    let boo = false;
    if(current < moment(this.startDate) || current >= moment(this.endDate)){
      boo = true;
    }
    return current && boo ;
  };

  cfo = travelUtil.createFormOption;

  getCurrencyList(){
    baseService.getAllCurrencyByLanguage('zh_cn', undefined, true).then(res => {
      this.setState({
        currencyList: res.data
      })
    })
  }

  //交换城市
  exchangeCity = () => {
    let fromCityItem = this.state.selectFromCity;
    let toCityItem = this.state.selectToCity;
    this.setState({
      selectToCity: fromCityItem,
      selectFromCity: toCityItem
    });
    this.props.form.setFieldsValue({'fromCity': toCityItem.vendorAlias});
    this.props.form.setFieldsValue({'toCity': fromCityItem.vendorAlias});
  };

  //选择出发城市
  selectFromCity = (cityObj) => {
    this.setState({selectFromCity: cityObj});
  };

  //选择到达城市
  selectToCity = (cityObj) => {
    this.setState({selectToCity: cityObj});
  };

  //提交
  toSubmit = (e) => {
    e.preventDefault();
    const {travelElement} =this.props.params;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (values.taxTotalAmount == 0) {
        message.error(messages('my-account.key75'/*金额不能为0*/));
        return;
      }
      if(travelElement&&!err){
        // values.trafficType = 1002;
        values.startDate = moment(moment(values.startDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        values.fromCityCode = this.state.selectFromCity.code;
        values.toCityCode = this.state.selectToCity.code;
        values.toCity = this.state.selectToCity.vendorAlias;
        values.fromCity = this.state.selectFromCity.vendorAlias;
        this.props.close(values);
      }else if(!err){
        // values.supplierOID = this.supply.supplierOID ? this.supply.supplierOID : null;
        values.startDate = moment(moment(values.startDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        if(this.state.formCtrl.fromCity.required && !this.state.selectFromCity.vendorAlias){
          message.error(messages('request.key368'/*出发城市不匹配或未点击选择*/));
          return ;
        } else if(this.state.formCtrl.toCity.required && !this.state.selectToCity.vendorAlias){
          message.error(messages('request.key369'/*到达城市不匹配或未点击选择*/));
          return ;
        }else{
          values.fromCityCode = this.state.selectFromCity.code;
          values.toCityCode = this.state.selectToCity.code;
          values.toCity = this.state.selectToCity.vendorAlias;
          values.fromCity = this.state.selectFromCity.vendorAlias;
        }
        // this.processTrainClass(values);
        this.setState({isLoading:true});
        if(!this.state.editing){
          travelService.travelTrainSubmit(this.state.params.oid,[values]).then(res => {
            this.submitFinish(messages('request.key189'/*已保存*/));
          }).catch(err=>{
            message.error(err.response.data.message);
            this.setState({isLoading:false});
          })
        }else {
          values.trainItineraryOID = this.props.params.editTrain.trainItineraryOID;
          travelService.updateTrain(values).then(res => {
            this.submitFinish(messages('request.key353'/*已更新*/))
          }).catch(err=>{
            message.error(err.response.data.message);
            this.setState({isLoading:false});
          })
        }
      }
    })
  };

  //处理火车座席
  processTrainClass = (values) => {
    if (values.seatClassCode && this.state.trainSeatClass && this.state.trainSeatClass.length) {
      this.state.trainSeatClass.map(trainSeat => {
        if (trainSeat.code === values.seatClassCode) {
          values.seatClass = trainSeat.name;
        }
      });
    }
  };

  submitFinish = (res) =>{
    this.setState({isLoading:false});
    this.closeTrainSlide();
    this.props.form.resetFields();
    message.success(res);
  };

  //清空已选城市数据type fromCity出发城市 toCity到达城市
  clearCityData = (type) => {
    if (type === 'fromCity') {
      this.setState({
        cityFromSearchResult: [],
        selectFromCity:{}
      });
      this.props.form.setFieldsValue({fromCity: ""});
    }
    if (type === 'toCity') {
      this.setState({
        cityToSearchResult: [],
        selectToCity:{}
      });
      this.props.form.setFieldsValue({toCity: ""});
    }
  };

  //选择供应商
  selectSupply = (index) => {
    this.supply = this.state.supplies[index];
    if (this.supply.function && this.supply.function[0]) {
      this.searchType = 'standard';//this.supply.function[0].locationVendorType;
      this.intEnable = this.supply.function[0].intEnable;
      this.clearHistory = this.supply.function[0].clearHistory;
    } else {
      this.searchType = 'standard';
      this.intEnable = true;
      this.clearHistory = false;
    }
    let country = 'all';
    if (!this.intEnable) {
      country = 'china';
    }
    //这里火车行程没有国际，所以不用额外处理国内，国际的tab，又有了，"其他"供应商要能支持选到国际的，但是不展示标签
    if (this.state.selectFromCity.code && !this.clearHistory) {
      travelService.isCityInVendor(this.searchType, this.state.selectFromCity.code, country).then(res => {
        if(res.data && res.data.alias){
          //this.state.selectFromCity上的vendorType这个字段是上一个供应商，现在没有用到这个字段，需要注意
          this.setState({
            cityFromSearchResult: [this.state.selectFromCity]
          });
        } else {
          this.clearCityData('fromCity');
        }
      }).catch(err=>{
        this.clearCityData('fromCity');
      });
    } else {
      this.clearCityData('fromCity');
    }
    if (this.state.selectToCity.code && !this.clearHistory) {
      travelService.isCityInVendor(this.searchType, this.state.selectToCity.code, country).then(res => {
        if(res.data && res.data.alias){
          //this.state.selectToCity上的vendorType这个字段是上一个供应商，现在没有用到这个字段，需要注意
          this.setState({
            cityToSearchResult: [this.state.selectToCity]
          });
        } else {
          this.clearCityData('toCity');
        }
      }).catch(err=>{
        this.clearCityData('toCity');
      });
    } else {
      this.clearCityData('toCity');
    }
    //cityFromSearchResult:[], cityToSearchResult:[]这还不能直接置空，不然已选中的在select中匹配不上
    this.setState({currentIndex: index, supplyId: this.supply.serviceName});
  }

 //获取供应商数据
  getSupplies = (type) => {
    travelService.travelSuppliers(type).then(res => {
      if(res['data']['2002']){
        let defaultIndex = 0;
        res['data']['2002'].map((item, index) => {
          if (item.userDefault) {
            defaultIndex = index;
          }
        });
        this.setState({
          supplies: res['data']['2002'],
          currentIndex: defaultIndex
        },() => {
          this.supply = this.state.supplies.length > 0 ? this.state.supplies[defaultIndex] : {};
          if (this.supply.function && this.supply.function[0]) {
            this.searchType = 'standard';//this.supply.function[0].locationVendorType;
            this.intEnable = this.supply.function[0].intEnable;
          }
        });
      }
    }).catch(err =>{
      message.error(err.response.data.message);
    })
  };

  //获取火车座席
  getTrainSeat = () => {
    travelService.getRuleConditionEnumV2(1002).then(res => {
      if (res.data && res.data.length) {
        this.setState({trainSeatClass: res.data});
      }
    }).catch(err =>{
      message.error(err.response.data.message);
    });
  };

  //重置表单
  resetForm = () =>{
    this.props.form.resetFields();
    delete this.props.params.editTrain;
    this.setState({
      editing:false,
    });
  }

  //关闭侧滑
  closeTrainSlide = () => {
    this.props.close();
  };

  render() {
    const {formCtrl, supplies, currentIndex, isLoading, cityFromSearchResult, cityToSearchResult, isStandard, trainSeatClass,
      promptList, currencyList} = this.state;
    const {getFieldDecorator} = this.props.form;
    let editData = travelUtil.isEmpty(this.props.params.editTrain);
    const {travelElement, travelInfo: {formCode}} = this.props.params;
    const formLayout = {
      maxRows: 6,
      minRows: 2
    };
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 18}
    }
    const formItemLayoutCity = {
      labelCol: {span: 8},
      wrapperCol: {span: 12}
    }
    const formItemLayoutAmt = {
      labelCol: {span: 4},
      wrapperCol: {span: 20}
    }
    const baseCurrency = this.props.company.baseCurrency;
    const isAmtRequired = formCtrl.taxTotalAmount && formCtrl.taxTotalAmount.required;
    return (
      <div className="travel-train">
        <Spin spinning={isLoading}>
          <TravelPrompt promptList={promptList} type={1002} />
          <Form>
            {false && !travelElement && <FormItem {...formItemLayout} label={messages('request.key354'/*消费商*/)}>
              <Row className="supplyRow">
                {
                  supplies.map((sup, index)=> {
                    return (
                      <Col key={sup.supplyId} span={4} className="supply" onClick={()=>this.selectSupply(index)}>
                        <Card hoverable
                              className={index==currentIndex?'card-on':'card-off'}
                              cover={sup.vendorIcon ? <img src={sup.vendorIcon.path}/> : null}>
                          <Popover content={sup.name}>
                            <span className="card-name">{sup.name}</span>
                          </Popover>
                        </Card>
                      </Col>
                    )
                  })
                }
              </Row>
            </FormItem>}
            {false && !travelElement && <Divider/>}
            <FormItem className="travel-margin-zero">
              <Row>
                <Col span={12}>
                  <FormItem {...formItemLayoutCity} label={messages('request.key376'/*出发城市*/)}>
                    {getFieldDecorator('fromCity', this.cfo(messages('request.key376'/*出发城市*/),{type:'str',value:editData.fromCity},!travelElement ? !formCtrl.fromCity.required: false))(
                      <TravelLocation intEnable={this.intEnable}
                                      vendorType={this.searchType}
                                      isEntity={false}
                                      formCode={formCode}
                                      onSelect={this.selectFromCity}
                                      isOldDataType={true}/>
                    )}
                  </FormItem>
                  <FormItem {...formItemLayoutCity} label={messages('request.key377'/*到达城市*/)}>
                    {getFieldDecorator('toCity', this.cfo(messages('request.key377'/*到达城市*/),{type:'str',value:editData.toCity},!travelElement ? !formCtrl.toCity.required : false))(
                      <TravelLocation intEnable={this.intEnable}
                                      vendorType={this.searchType}
                                      isEntity={false}
                                      formCode={formCode}
                                      onSelect={this.selectToCity}
                                      isOldDataType={true}/>
                    )}
                  </FormItem>
                </Col>

                <div className="line-top"></div>
                <Button className={this.props.language.code === 'zh_cn' ? "exchange-city" : "exchange-city-en"} onClick={this.exchangeCity}>{messages('request.key378'/*换*/)}</Button>
                <div className="line-bottom"></div>

                <Col span={12}>
                  <FormItem {...formItemLayoutCity} label={messages('request.key379'/*出发日期*/)}>
                    {getFieldDecorator('startDate', this.cfo(messages('request.key379'/*出发日期*/),{type:'moment',value:editData.isEmpty?this.startDate:editData.startDate}))
                    (<DatePicker disabledDate={this.disabledDate}/>)}
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
            {
              formCtrl.taxTotalAmount && formCtrl.taxTotalAmount.show && <Row>
                <FormItem {...formItemLayoutAmt} label={messages('mcd.total.tax.amt'/*含税总金额*/)} required={isAmtRequired}>
                  <Col span={4}>
                    <FormItem>
                      {getFieldDecorator('currency',this.cfo(messages('common.currency'/*币种*/),{type:'str',value:editData.currency || baseCurrency}, !isAmtRequired))(
                        <Select className="for-train-amt"
                                optionLabelProp="label"
                                getPopupContainer={() => document.getElementsByClassName('for-train-amt')[0]}>
                          {
                            currencyList.length>0 && currencyList.map(item => {
                              return <Option key={item.currency} label={item.currency}>{item.currency} {item.currencyName}</Option>
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem>
                      {getFieldDecorator('taxTotalAmount',this.cfo(messages('mcd.total.tax.amt'/*含税总金额*/),{type:'number',value:editData.taxTotalAmount}, !isAmtRequired))(
                        <InputNumber className="train-price" min={0} placeholder={messages('setting.key796'/*请输入金额*/)}/>
                      )}
                    </FormItem>
                  </Col>
                </FormItem>
              </Row>
            }
          </Form>
        </Spin>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button type="primary" loading={isLoading} onClick={this.toSubmit}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.closeTrainSlide}>{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }
}


function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language
  };
}

const wrappedTravelTrain = Form.create()(TravelTrain);

export default connect(mapStateToProps)(wrappedTravelTrain);
